package com.hxzy.springbootrocketproducer.service;

import com.alibaba.fastjson.JSONObject;
import com.hxzy.springbootrocketproducer.dto.UserChargeDTO;
import lombok.extern.log4j.Log4j2;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * 分布式事务 生产者(只能用做冲值用的)
 */
@Log4j2
@Component
public class MQTXProducerService {

    //话题
    private static final String Topic = "RLT_ACCOUNT_TOPIC";
    //标签
    private static final String Tag = "charge";



    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    /**
     * 先向RocketMQ Server发送半消息
     * @param userCharge 用户充值信息
     */
    public TransactionSendResult sendHalfMsg(UserChargeDTO userCharge) {
        // 生成生产事务id
        String transactionId = UUID.randomUUID().toString().replace("-", "");
        log.info("【发送半消息】transactionId={}", transactionId);

        // 发送事务消息（参1：生产者所在事务组，参2：topic+tag，参3：消息体(可以传参)，参4：发送参数）
        TransactionSendResult sendResult = rocketMQTemplate.sendMessageInTransaction(
                Topic + ":" + Tag,
                MessageBuilder.withPayload(userCharge).setHeader(RocketMQHeaders.TRANSACTION_ID, transactionId).build(),
                userCharge);

        log.info("【发送半消息】sendResult={}", JSONObject.toJSONString(sendResult));
        return sendResult;
    }

}
